import React, { useEffect, useRef, useState } from 'react'
import ProTable from '@ant-design/pro-table'
import ProCard, { StatisticCard } from '@ant-design/pro-card'
import RcResizeObserver from 'rc-resize-observer'
import ProTableConfig from '@/pages/Report/ProTableConfig'
import { loginReport, loginReportCount, loginReportExport } from '@/services/report'
import { Button } from 'antd'
import GetTime from '@/components/GetTime'
import { nowTime } from '@/components/GetTime/getTime.js'

const { Statistic } = StatisticCard

export default function Login () {
  const [responsive, setResponsive] = useState(false)
  /** 总登录次数 **/
  const [allCount, setAllCount] = useState(undefined)
  /** 设置 loading **/
  const [loading, setLoading] = useState(false)
  const actionRef = useRef()

  useEffect(async () => {
    // 统计日志
    const count = await loginReportCount()

    // 历史登录次数
    let allNum = count.reduce(function (init, item) {
      return init + item.num
    }, 0)

    // 数据概览数据
    let allCount = {
      today: count[count.length - 1].num,
      yesterday: count[count.length - 2].num,
      allNum,
      average: Math.ceil(allNum / count.length)
    }

    setAllCount(allCount)
  }, [])

  /** 表单请求 **/
  const tableRequest = async (params) => {
    {
      setLoading(true)
      // 更改默认属性名 current
      params = JSON.parse(JSON.stringify(params).replace(/current/g, 'page'))
      const data = await loginReport(params)
      setLoading(false)
      return {
        data: data.data,
        success: true,
        total: data.meta.pagination.total
      }
    }
  }

  /**
   * 导出登录日志
   */
  const exportLogs = async () => {
    const response = await loginReportExport()
    const url = window.URL.createObjectURL(new Blob([response], { type: 'application/x-xls' }))
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', `登录日志-${nowTime()}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  /** 设置 table 字段 **/
  const columns = [
    {
      title: '编号',
      key: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '登录用户',
      key: 'username',
      dataIndex: 'user_id',
      render: (text, record) => {
        return record.user.username
      },
    },
    {
      title: '登录ip',
      key: 'ip',
      dataIndex: 'ip',
      hideInSearch: true,
    },
    {
      title: '时间区间',
      key: 'dateTimeRange',
      dataIndex: 'createdAtRange',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1]
          }
        },
      },
    },
    {
      title: '登录时间',
      key: 'createdAt',
      dataIndex: 'created_at',
      valueType: 'fromNow',
      hideInSearch: true
    },
    {
      title: '登录时间',
      key: 'created_at',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      hideInSearch: true,
      sorter: true
    },
  ]

  return (
    <>
      <RcResizeObserver
        key="resize-observer"
        onResize={(offset) => {
          setResponsive(offset.width < 640)
        }}
      >
        <ProCard
          title="数据概览"
          extra={<GetTime/>}
          split={responsive ? 'horizontal' : 'vertical'}
          headerBordered
          ghost={false}
          hoverable
          bordered
        >
          <ProCard split="horizontal">
            <ProCard split="horizontal">
              <ProCard split="vertical">
                <StatisticCard
                  hoverable
                  bordered={true}
                  gutter={2}
                  statistic={{
                    title: '今日登录',
                    suffix: '次',
                    value: allCount ? allCount.today : loading,
                    description: <Statistic
                      title="较昨日登录次数"
                      value={allCount ? allCount.today - allCount.yesterday : 0}
                      trend={(allCount ? allCount.today - allCount.yesterday : 0) > 0 ? 'up' : 'down'}/>,
                  }}
                />
                <StatisticCard
                  hoverable
                  bordered={true}
                  gutter={2}
                  statistic={{
                    title: '昨日登录',
                    suffix: '次',
                    value: allCount ? allCount.yesterday : loading,
                    description: <Statistic
                      title="平均每日登录"
                      value={allCount ? allCount.yesterday - allCount.average : 0}
                      trend={(allCount ? allCount.yesterday - allCount.average : 0) > 0 ? 'up' : 'down'}/>,
                  }}
                />
              </ProCard>
              <ProCard split="vertical">
                <StatisticCard
                  hoverable
                  bordered={true}
                  gutter={2}
                  statistic={{
                    title: '历史登录',
                    value: allCount ? allCount.allNum : loading,
                    suffix: '次',
                  }}
                />
                <StatisticCard
                  hoverable
                  bordered={true}
                  gutter={2}
                  statistic={{
                    title: '平均每日登录',
                    suffix: '次',
                    value: allCount ? allCount.average : loading,
                  }}
                />
              </ProCard>
            </ProCard>
          </ProCard>
        </ProCard>
      </RcResizeObserver>
      <ProTable
        {...ProTableConfig}
        headerTitle="登录日志表格"
        actionRef={actionRef}
        columns={columns}
        dateFormatter="string"
        tableLayout="auto"
        params={{ include: 'user' }}
        request={(params) => tableRequest(params)}
        toolBarRender={() => {
          return <Button
            key="button"
            type="primary"
            onClick={() => exportLogs()}
          >
            导出
          </Button>
        }}
      />
    </>
  )
};
